import Snake from "./Snake";
import Food from "./Food";
import ScorePanel from "./ScorePanel";
/**
 * 游戏控制
 */
class GameControl {
    snake: Snake;
    food: Food;
    score_panel: ScorePanel;

    //蛇的移动方向
    direction: string = "";

    //游戏是否结束
    isLive = true;

    constructor() {
        this.score_panel = new ScorePanel();
        this.snake = new Snake();
        this.food = new Food();
        //改变食物的位置
        this.food.change();
        this.init();

    }

    //初始化
    init() {
        //绑定键盘按下事件
        document.addEventListener('keydown', this.keydownHandler.bind(this))
        this.run()
    }

    //创建键盘按下响应函数
    keydownHandler(event: KeyboardEvent) {
        switch (event.key) {
            case "ArrowUp":
            case "Up":
            case "ArrowDown":
            case "Down":
            case "ArrowLeft":
            case "Left":
            case "ArrowRight":
            case "Right":
                this.direction = event.key;
                break;
            default:
                break;
        }
    }

    //蛇移动方法
    run() {
        let X = this.snake.x;
        let Y = this.snake.y;
        switch (this.direction) {
            case "ArrowUp":
            case "Up":
                Y -= 10
                break;
            case "ArrowDown":
            case "Down":
                Y += 10;
                break;
            case "ArrowLeft":
            case "Left":
                X -= 10;
                break;
            case "ArrowRight":
            case "Right":
                X += 10;
                break;
            default:
                break;
        }

        //检查是否吃到食物
        this.checkEat(X, Y)

        try {
            this.snake.x = X;
            this.snake.y = Y;
        } catch (e) {
            alert(e);
            this.isLive = false;
        }


        //开启定时器
        //如果游戏没有结束,开启定时器
        this.isLive && setTimeout(this.run.bind(this), 300 - (this.score_panel.mLevel - 1) * 30)
    }

    //吃食物
    checkEat(x: number, y: number) {
        if (x === this.food.x && y === this.food.y) {
            this.food.change()
            this.score_panel.addScore()
            this.snake.addBody()
        }

    }

}

export default GameControl;